"""
Copyright (c) 2023 - present SKbioinfo
"""
from flask_restful import Resource
from flask import request,jsonify,current_app
from flask_jwt_extended import jwt_required
from datetime import datetime
import glob
import os

'''URL:/api/customData/AddCustomData/<string:tag>'''
class interfaceAddCustomData(Resource):
    def __init__(self):
        customPath=current_app.config.get("CUSTOM_DATA_PATH")
        self.map={
            "rNGS":[
                f"{customPath}/rNGS"
            ],
        }
    def _file_pairs(self,dirPath:str,read_type:str):
        patterns = [
            f"{dirPath}/*_{read_type}*.fastq",
            f"{dirPath}/*_{read_type}*.fq",
            f"{dirPath}/*_{read_type}*.fastq.gz",
            f"{dirPath}/*_{read_type}*.fq.gz"
        ]
        r1 = []
        for pattern in patterns:
            r1.extend(glob.glob(pattern))
        fileList={}
        for r in r1:
            r2=""
            if read_type == 'R1':
                r2=r.replace("_R1","_R2")
            elif read_type == '1':
                r2=r.replace("_1","_2")
            r2_path=""
            if os.path.islink(r2):
                r2_path = os.path.realpath(r2)
            else:
                r2_path=r2
            if os.path.exists(r2_path):
                sample_name="_".join(os.path.basename(r).split("_")[:-1])
                fileList[sample_name]=[r,r2]
            else:
                sample_name="_".join(os.path.basename(r).split("_")[:-1])
                fileList[sample_name]=[r,"-"]
        return fileList
    def _create_id(self):
        timestamp = datetime.now().strftime('%Y%m%d%H%M%S%f')
        return f"D{timestamp}"
    @jwt_required()
    def get(self,tag):
        try:
            response=jsonify(self.map[tag])
            response.status=202
            return response
        except Exception as e:
            response = jsonify({})
            response.status = 404
            return response  
    @jwt_required()
    def post(self,tag):
        try:
            if tag == 'rNGS':
                page=request.json["pagination"]["page"]
                limit=request.json["pagination"]["limit"]
                files=[]
                for dirPath in request.json["QueryPath"]:
                    filesList_1_2=self._file_pairs(dirPath,"1")
                    fileList_R1_R2=self._file_pairs(dirPath,"R1")
                    filesList={**fileList_R1_R2,**filesList_1_2}
                    split_id=self._create_id()
                    for sample_name,value in filesList.items():
                        existed_valid={
                            os.path.basename(file):( 1 if os.path.exists(file) else -1) 
                            for file in filesList[sample_name]
                        }
                        exist_tag=";".join([  
                            f'{key}数据不存在' for key,value in existed_valid.items() if value==-1
                        ])
                        files.append({
                            "split_id":split_id,
                            "dirPath":dirPath,
                            "sample_name":sample_name,
                            "raw_1":filesList[sample_name][0],
                            "raw_2":filesList[sample_name][1],
                            "valid":list(existed_valid.values())[0] + list(existed_valid.values())[1],
                            "existed_tag":exist_tag
                        })
                files_slice=files[(page-1)*limit:page*limit]
                response=jsonify({"total":len(files),"data":files_slice})
                response.status=202
                return response
            else:
                response=jsonify([])
                response.status=300
                return response
        except Exception as e:
            response = jsonify([])
            response.status = 404
            return response     
